package com.jt.service;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Set;



@Service
public class MenuServiceImpl implements MenuService {
    private static final String KEY_PREFIX ="menu:";
    //注入方案1
//    @Autowired
//    private RedisTemplate redisTemplate;
//    @Autowired
//    private MenuMapper menuMapper;
    private static final Logger log=
            LoggerFactory.getLogger(MenuServiceImpl.class);
    //注入方案2,
    private MenuMapper menuMapper;
    private ValueOperations valueOperations;

    public MenuServiceImpl(MenuMapper menuMapper,
                           RedisTemplate redisTemplate) {
        this.menuMapper = menuMapper;
        this.valueOperations = redisTemplate.opsForValue();
    }
    @Override
    public Menu selectById(Long id) {
        //1.从redis获取菜单信息,有则直接返回
       // ValueOperations valueOperations =
               // redisTemplate.opsForValue();
        Object obj = valueOperations.get("menu:" + id);
        if(obj!=null){
            log.info("Data from Redis Cache");
            return (Menu)obj;
        }
        log.info("Data from MySQL");
        //2.从mysql数据库中查询菜单信息
        Menu menu=menuMapper.selectById(id);
        //3.将数据中查询到的菜单信息存储到redis
        valueOperations.set("menu:"+id,
                menu,
                Duration.ofSeconds(60*60));
        //4.返回菜单对象
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
        log.info("insert.before.menu={}",menu);
        menuMapper.insert(menu);
        log.info("insert.after.menu={}",menu);
       // ValueOperations valueOperations = redisTemplate.opsForValue();
       valueOperations.set(KEY_PREFIX+menu.getId(),
                menu,Duration.ofSeconds(60*60));
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
       //1,更新mysql数据
       menuMapper.updateById(menu);
       //2,更新缓存数据
       // ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(),
                menu,Duration.ofSeconds(60*60));
        return menu;
    }


}

